import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TestClient04{
    public static void main(String[] args) {
        Socket socket = null;
        try {
            // 1. 连接服务器
            socket = new Socket("127.0.0.1", 8989);
            System.out.println("已连接到服务器：" + socket.getRemoteSocketAddress());

            // 2. 使用 try-with-resources 管理流
            try (
                Scanner scanner = new Scanner(System.in);
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))
            ) {
                String input;
                while (true) {
                    // 3. 读取用户输入
                    System.out.print("请输入消息 (输入 quit 退出): ");
                    input = scanner.nextLine();

                    // 4. 发送消息到服务器
                    bw.write(input);
                    bw.newLine();
                    bw.flush();

                    // 5. 处理退出逻辑
                    if ("quit".equalsIgnoreCase(input)) {
                        System.out.println("客户端即将关闭");
                        break;
                    }

                    // 6. 接收服务器响应
                    String response = br.readLine();
                    System.out.println("服务器返回: " + response);
                }
            }
        } catch (IOException e) {
            System.err.println("客户端通信失败: " + e.getMessage());
        } finally {
            // 7. 关闭连接
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.println("关闭连接失败: " + e.getMessage());
                }
            }
        }
    }
}